import router from '@/router'
import { RouteLocationRaw } from 'vue-router'
import { MenuState } from '@/interfaces/api/menu'
import { h } from 'vue'
import { NIcon } from 'naive-ui'
import * as icc from '@vicons/ionicons5'

let iccs = icc as any

/**
 * @description: 路由的push跳转
 * @param {RouteLocationRaw} options router push的参数
 */
export const routerPush = (options: RouteLocationRaw) => {
  router.push(options)
}

/**
 * @description: 路由的replace跳转
 * @param {RouteLocationRaw} options router push的参数
 */
export const routerReplace = (options: RouteLocationRaw) => {
  router.replace(options)
}

/**
 * @description: 获取本地存储的内容
 * @param {string} key 获取本地存储对象的键
 * @return {T} 根据函数泛型返回数据
 */
export const getLocalStorage = <T>(key: string): T => {
  let obj = JSON.parse(window.localStorage.getItem(key) || '{}') as T
  return obj
}

/**
 * @description: 设置本地储存的数据
 */
export const setLocalStorage = (key: string, value: any) => {
  window.localStorage.setItem(key, JSON.stringify(value))
}

/**
 * @description: 动态挂载路由
 */
export const addItem = (menu: MenuState) => {
  if (!menu.componentPath || menu.componentPath === '') {
    return
  }
  router.addRoute('layout', {
    path: menu.path,
    name: menu.menuName,
    component: () => import(`../../views/${menu.componentPath}`),
    meta: {
      title: menu.title,
    },
    redirect: menu.redirect,
  })
  if (menu.children.length > 0) {
    menu.children.forEach((item) => {
      addItem(item)
    })
  }
}
/**
 * @description: 转换菜单栏需要的数据类型
 */
export const NMenuColmenu = ({
  label,
  key,
  data,
}: {
  label: string
  key: string
  data: MenuState[]
}) => {
  let list: any = data.map((item) => {
    let children = []
    if (item.children && item.children.length > 0) {
      children = NMenuColmenu({ label, key, data: item.children })
    }
    let obj = {
      label: item[label as 'title'],
      key: item[key as 'menuName'],
      children,
      id: item.id,
      icon: renderIcon(iccs[item.iocn]),
    }

    if (obj.children.length <= 0) delete obj.children
    return obj
  })
  return list
}

export function renderIcon(icon: any, size: string = '') {
  return () => h(NIcon, { size }, { default: () => h(icon) })
}

export function renderIconKey(key: string, size: string) {
  return renderIcon(iccs[key], size)()
}

/**
 * 中划线字符驼峰
 * @param {*} str 要转换的字符串
 */
export function toHump(str: string): string {
  if (!str) return str
  return str
    .replace(/\-(\w)/g, function (all, letter) {
      return letter.toUpperCase()
    })
    .replace(/(\s|^)[a-z]/g, function (char) {
      return char.toUpperCase()
    })
}
